const { success, failure } = require("../../utils/responses");
const categoriesServices = require("../../services/learn/categoriesService");

/**
 * 查询分类列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.list = async (req, res) => {
  try {
    // 分页查询
    const { count, rows, currentPage, pageSize } =
      await categoriesServices.list(req);
    // 返回
    success(res, "分类查询成功", {
      lists: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 查询分类列表
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.all = async (req, res) => {
  try {
    const rows = await categoriesServices.all(req);
    // 返回
    success(res, "分类查询成功", {
      lists: rows,
    });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 查询分类详情
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.details = async (req, res) => {
  try {
    const category = await categoriesServices.getById(req);
    success(res, "查询分类成功", { category });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 创建分类
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.add = async (req, res) => {
  try {
    const body = filterBody(req);
    const category = await categoriesServices.create(body);
    success(res, "创建分类成功", category, 201);
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 删除分类
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.del = async (req, res) => {
  try {
    await categoriesServices.del(req.body.id);
    success(res, "删除分类成功");
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 更新分类
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
exports.update = async (req, res) => {
  try {
    const body = filterBody(req);
    const category = await categoriesServices.update(req.body.id, body);
    success(res, "更新分类成功", { category });
  } catch (error) {
    failure(res, error);
  }
};

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {{name, rank: (number|*)}}
 */
function filterBody(req) {
  return {
    name: req.body.name || req.query.name,
    rank: req.body.rank || req.query.rank,
  };
}
